/**
 * Thinking Timeline
 * 
 * 思维链时间线组件 - 按时间顺序展示思维步骤
 */

import * as React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ThinkingStepCard } from './ThinkingStepCard';
import type { ThinkingChain } from '@/types/thinking';
import { cn } from '@/lib/utils';

export interface ThinkingTimelineProps {
  /** 思维链数据 */
  chain: ThinkingChain;
  /** 是否显示持续时间 */
  showDuration?: boolean;
  /** 是否显示置信度 */
  showConfidence?: boolean;
  /** 是否启用动画 */
  enableAnimation?: boolean;
  /** 类名 */
  className?: string;
}

/**
 * 思维链时间线组件
 */
export function ThinkingTimeline({
  chain,
  showDuration = true,
  showConfidence = false,
  enableAnimation = true,
  className,
}: ThinkingTimelineProps) {
  // 展开状态管理
  const [expandedSteps, setExpandedSteps] = React.useState<Set<string>>(new Set());

  // 切换步骤展开状态
  const toggleStep = React.useCallback((stepId: string) => {
    setExpandedSteps(prev => {
      const next = new Set(prev);
      if (next.has(stepId)) {
        next.delete(stepId);
      } else {
        next.add(stepId);
      }
      return next;
    });
  }, []);

  // 格式化总时长
  const formatTotalDuration = (ms: number) => {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    const minutes = Math.floor(ms / 60000);
    const seconds = Math.floor((ms % 60000) / 1000);
    return `${minutes}m ${seconds}s`;
  };

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1,
      },
    },
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.3,
        ease: 'easeOut',
      },
    },
  };

  if (!chain.steps || chain.steps.length === 0) {
    return (
      <div className={cn('text-center py-8 text-muted-foreground', className)}>
        <p className="text-sm">暂无思维步骤</p>
      </div>
    );
  }

  return (
    <div className={cn('thinking-timeline space-y-4', className)}>
      {/* 时间线头部 */}
      <div className="flex items-center justify-between text-sm">
        <div className="font-medium">
          思维过程 ({chain.steps.length} 个步骤)
        </div>
        {showDuration && (
          <div className="text-muted-foreground">
            总耗时: {formatTotalDuration(chain.totalDuration)}
          </div>
        )}
      </div>

      {/* 时间线主体 */}
      {enableAnimation ? (
        <motion.div
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className="space-y-3"
        >
          {chain.steps.map((step, index) => (
            <motion.div
              key={step.id}
              variants={itemVariants}
            >
              <ThinkingStepCard
                step={step}
                index={index}
                expanded={expandedSteps.has(step.id)}
                onToggle={() => toggleStep(step.id)}
                showDuration={showDuration}
                showConfidence={showConfidence}
              />
            </motion.div>
          ))}
        </motion.div>
      ) : (
        <div className="space-y-3">
          {chain.steps.map((step, index) => (
            <ThinkingStepCard
              key={step.id}
              step={step}
              index={index}
              expanded={expandedSteps.has(step.id)}
              onToggle={() => toggleStep(step.id)}
              showDuration={showDuration}
              showConfidence={showConfidence}
            />
          ))}
        </div>
      )}

      {/* 时间线尾部 - 摘要 */}
      {chain.summary && (
        <div className="text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
          {chain.summary}
        </div>
      )}
    </div>
  );
}

